package com.mydemo.common.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.mydemo.common.pojo.LoginUser;
import com.mydemo.common.pojo.RespResult;
import com.mydemo.common.utils.JWTUtils;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
 * JWT过滤器
 *
 * @author Last_Island
 * @version 1.0
 */
public class JWTFilter extends OncePerRequestFilter {
    private static final Logger log = LoggerFactory.getLogger(JWTFilter.class);
    @Autowired
    private JWTUtils jwtTokenUtil;
    @Value("${token.header}")
    private String tokenHeader;
    @Value("${token.tokenHead}")
    private String tokenHead;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {

        // 获取带有前缀的token
        String authHeader = request.getHeader(this.tokenHeader);
        // 判断token 是否为空或真的带有前缀
        if (authHeader != null && authHeader.startsWith(this.tokenHead)) {
            // 获取真正的token
            String authToken = authHeader.substring(this.tokenHead.length());// The part after "Bearer "
            String username = jwtTokenUtil.getUserNameFromToken(authToken);
            log.info("checking username:{}", username);
            // 获取当前登录的用户
            if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                try {
                    LoginUser loginUser = jwtTokenUtil.getLoginUser(authToken);
                    loginUser.getSysUser().setPassword(null);
                    // 判断token是否失效
                    if (jwtTokenUtil.validateToken(authToken, loginUser)) {
                        UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
                        authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                        log.info("authenticated user:{}", username);
                        SecurityContextHolder.getContext().setAuthentication(authentication);
                    }
                } catch (Exception e) {
                    ObjectMapper mapper = new ObjectMapper();
                    response.setContentType("application/json;charset=UTF-8");
                    response.setStatus(200);
                    response.getWriter().write(mapper.writeValueAsString(RespResult.error(403, e.getMessage())));
                    return;
                }
            }
        }
        filterChain.doFilter(request, response);
    }
}
